package net.p2pcdn.core.order.service;

import net.p2pcdn.core.order.domain.Contract;
import net.p2pcdn.core.order.domain.Order;
import net.p2pcdn.core.order.domain.OrderDetail;
import net.p2pcdn.core.order.repository.OrderDetailRepository;
import net.p2pcdn.core.order.repository.OrderRepository;
import net.p2pcdn.core.product.domain.Product;
import net.p2pcdn.core.product.domain.ProductType;
import net.p2pcdn.core.product.service.ProductService;
import net.p2pcdn.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @author zx
 */
@Service
public class TrafficPackageOrderHandler implements OrderHandler {
    @Autowired
    private OrderHandlerFactory orderHandlerFactory;
    @Resource
    private OrderRepository orderRepository;
    @Resource
    private OrderDetailRepository orderDetailRepository;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private ContractService contractService;

    @Override
    public ProductType supportType() {
        return ProductType.PACKAGE;
    }

    @Override
    public void handle(OrderDetail detail) {
        Order order = this.orderRepository.selectByPrimaryKey(detail.getOrderId());
        Optional<Contract> contract = contractService.findLastUnEffectiveContract(order.getBuyer(), detail.getItemId());
        Product product = productService.getProduct(detail.getItemId());
        List<Contract> newContracts;
        if (!contract.isPresent()) {
            newContracts = Contract.generateContracts(order, null, product, detail.getDomains());
            newContracts.get(0).setStatus(Contract.EFFECTIVE);
        } else {
            Contract lastContract = contract.get();
            newContracts = Contract.generateContracts(order, lastContract.getExpireTime(), product, detail.getDomains());
        }
        contractService.saveContract(newContracts, getChangeType(order.getPayType()));
    }


    @Override
    public void afterPropertiesSet() {
        orderHandlerFactory.addHandler(supportType(), this);
    }
}
